<template>
  <img v-if="!loaded" ref="fakeImgEl" :src="BASE_IMG" alt="" />
  <img v-else :src="src" alt="" />
</template>

<script>
import { ref } from 'vue'

import { loadImg } from '@/utils/media'
import { useDomObserver } from '@/hook/utils'
import BASE_IMG from 'static/images/headimg.webp'

export default {
  name: 'BaseImg',
  props: {
    src: {
      default: ''
    },
    lazy: {
      default: true
    }
  },
  setup(props) {
    const fakeImgEl = ref()
    const loaded = ref(false)
    const load = async () => {
      if (!props.src) return
      await loadImg(props.src)
      loaded.value = true
    }

    if (props.lazy) {
      useDomObserver(fakeImgEl, load)
    } else {
      load()
    }

    return {
      loaded,
      fakeImgEl,
      BASE_IMG
    }
  }
}
</script>

<style lang="scss" scoped>
img {
  cursor: pointer;
  user-select: none;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
